#include <my_header.h>

typedef struct share_value_s
{
    int flag;
    int ticket_num;
    pthread_cond_t cond;
    pthread_mutex_t mutex;
}share_value_t;

void * threadFunc_sell(void * arg);
void * threadFunc_add(void * arg);
/* usage */
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,1);
    share_value_t share_value;
    share_value.ticket_num = 20;
    share_value.flag = 0;
    pthread_mutex_init(&share_value.mutex,NULL);
    pthread_cond_init(&share_value.cond,NULL);

    printf("Today ticket_num = %d\n",share_value.ticket_num);
    pthread_t tid[3];
    pthread_create(&tid[0],NULL,threadFunc_sell,&share_value);
    pthread_create(&tid[1],NULL,threadFunc_sell,&share_value);
    pthread_create(&tid[2],NULL,threadFunc_add,&share_value);

    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    pthread_join(tid[2],NULL);

    return 0;
}

void * threadFunc_add(void * arg)
{
    share_value_t * pshare_value = (share_value_t *)arg;
    pthread_mutex_lock(&pshare_value->mutex);
    while(pshare_value->ticket_num > 10)
    {
        pthread_cond_wait(&pshare_value->cond,&pshare_value->mutex);
    }
    pshare_value->ticket_num += 10;
    printf("Thread1 adds, ticket_num = %d\n",pshare_value->ticket_num);
    pthread_mutex_unlock(&pshare_value->mutex);
    sleep(1);
    pthread_exit(NULL);
}

void * threadFunc_sell(void * arg)
{
    share_value_t * pshare_value = (share_value_t *)arg;
    while(pshare_value->ticket_num > 0)
    {
        pthread_mutex_lock(&pshare_value->mutex);
        while (pshare_value->ticket_num <= 0)
        {
            pthread_mutex_unlock(&pshare_value->mutex);
            break;
        }
        pshare_value->ticket_num --;
        printf("Thread sells ,ticket_num = %d\n",pshare_value->ticket_num);
        if(pshare_value->ticket_num <= 10)
        {
            pthread_cond_signal(&pshare_value->cond);
        }
        pthread_mutex_unlock(&pshare_value->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
